package vip.xiaonuo.facedoor.modular.reactor;

import static reactor.event.selector.Selectors.$;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import javax.annotation.Resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.Reactor;
import reactor.event.Event;
import reactor.function.Consumer;
import vip.xiaonuo.facedoor.modular.device.entity.DeviceCategory;
import vip.xiaonuo.facedoor.modular.memberfeatures.entity.MemberFeatures;
import vip.xiaonuo.facedoor.modular.memberfeatures.enums.MemberFeaturesTypeEnum;
import vip.xiaonuo.facedoor.modular.memberfeatures.service.MemberFeaturesService;
import vip.xiaonuo.facedoor.modular.topic.EventTopic;

@Service
public class MemberFaceFeatureAddListener implements Consumer<Event<MemberFeatures>>, InitializingBean {

    @Resource
    private MemberFeaturesService memberFeaturesService;

    @Autowired
    private Reactor reactor;

    @Override
    public void accept(Event<MemberFeatures> event) {
        MemberFeatures memberFeatures = event.getData();
        if (ObjectUtil.equal(memberFeatures.getPlatform(), DeviceCategory.SUB_TYPE_FACE)||ObjectUtil.equal(memberFeatures.getPlatform(), DeviceCategory.SUB_TYPE_STORE)) {
            // 执行人脸门禁  特征值分类保存
            executeSubTypeFace(memberFeatures);
        }
    }

    private void executeSubTypeFace(MemberFeatures memberFeatures) {
        MemberFeatures dbFace = null;
        // 内部人员
        if (ObjectUtil.equal(memberFeatures.getType(), MemberFeaturesTypeEnum.MEMBER.getValue())) {
            dbFace = memberFeaturesService.getOne(new LambdaQueryWrapper<MemberFeatures>()
                    .eq(MemberFeatures::getDwMemberUserId, memberFeatures.getDwMemberUserId())
                    .eq(MemberFeatures::getPlatform, memberFeatures.getPlatform()).last("for update"));// 锁下表 防止查询的时候事务还没提交
            // 访客
        } else if (ObjectUtil.equal(memberFeatures.getType(), MemberFeaturesTypeEnum.VISITOR.getValue())) {
            dbFace = memberFeaturesService.getOne(new LambdaQueryWrapper<MemberFeatures>()
                    .eq(MemberFeatures::getDwVisitorId, memberFeatures.getDwVisitorId())
                    .eq(MemberFeatures::getPlatform, memberFeatures.getPlatform()).last("for update")); // 锁下表 防止查询的时候事务还没提交
        }
        if (dbFace != null) {
            dbFace.setValue(memberFeatures.getValue());
            memberFeaturesService.updateById(dbFace);
            return;
        }
        memberFeaturesService.save(memberFeatures);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        reactor.on($(EventTopic.MEMBER_FACE_VALUE_ADD), this);
    }
}
